import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/base_page/base_page.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/utils/my_event_bus_util.dart';
import 'package:hxdj/message/rongcloud/rc_chat/model/rc_chat_model.dart';
import 'package:hxdj/message/rongcloud/rc_engine_manager.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

class MessageViewModel extends BaseViewModel {
  int allUnreadMessageCount = 0;

  Map<String, dynamic> dataList = {};

  List<ConversationMessage> conversationMessageList = [];

  late StreamSubscription onEventResult;

  MessageViewModel() {
    onEventResult = MyEventBusUtil.onEventResult((value) {
      //接收到信息
      if (value.tag == MyEventBusTag.onMessageReceived) {
        Map<String, String> arg = Map<String, String>.from(value.result);
        late String left = arg['left']!;
        if (left == "0") {
          // 更新最近会话
          Map<String, dynamic> messageMap = json.decode(arg['message']!);
          ChatMessageBaseModel messageBaseModel = ChatMessageBaseModel.fromJson(messageMap);

          updateRecentConversationList(messageBaseModel.targetId!,isNeedAll: true);
        }
      }
    });
  }

  dismiss() {
    onEventResult.cancel();
  }

  //请求消息的相关数据
  requetsData({bool isFrist = false}) async {
    if (isFrist) {
      setState(ViewState.loading);
    }
    dataList.clear();

    await requestSystemMessage();

    await getRecentConversationList();

    //获取所有的未读消息的数量, IM & 系统
    await getAllUnreadMessageCount();
  }

  //登录IM
  loginIM() async {
    //获取当前登录账号的状态
    //登录IM的相关操作
    //登录IM test5 的时候, 要 断一下, 不然报错 34001
    MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
    await RCEngineManager().disconnectIM();
    await RCEngineManager().connectIM(globalViewModel.userModel!.imPass ?? "",
        callback: RCIMIWConnectCallback(onDatabaseOpened: (int? code) {
          debugPrint("登录IM结果是 onDatabaseOpened code ==  $code");
        }, onConnected: (int? code, String? userId) {
          debugPrint("登录IM结果是 onConnected code $code + userId = $userId ");
        }));
    requetsData(isFrist: true);
  }

  //获取所有的未读消息的数量, IM & 系统
  Future<int> getAllUnreadMessageCount() async {
    /// 获取所有未读数
    return await RCEngineManager().getTotalUnreadCount(
        callback: IRCIMIWGetTotalUnreadCountCallback(onSuccess: (int? value) {
      debugPrint("获取所有未读数 value $value");
      allUnreadMessageCount = value ?? 0;
      allUnreadMessageCount = allUnreadMessageCount;
      notifyListeners();
    }, onError: (int? code) {
      debugPrint("获取所有未读数 code $code");
    }));
  }

  //清除所有消息的未读消息, 还有系统消息, 需要调用接口
  cleanAllUnreadMessage() async {
    EasyLoading.show(status: "请稍等...");
    //先遍历所有未读消息List
    for (var element in conversationMessageList) {
      if (element.unreadCount! > 0) {
        //清除所有未读消息
        RCEngineManager().clearUnreadCount(element.targetId!, element.lastMessage?.sentTime ?? 0);
      }
    }

    await getRecentConversationList();
    //获取所有的未读消息的数量, IM & 系统
    await getAllUnreadMessageCount();
    EasyLoading.dismiss();

    notifyListeners();
  }

  //获取最近会话
  Future<bool> getRecentConversationList() async {
    //加载最近会话
    return await RCEngineManager().getRecentConversationList(
        callback: IRCIMIWGetConversationsCallback(onSuccess: (List<RCIMIWConversation>? value) async {
      conversationMessageList.clear();

      List<String> userIds = [];
      value?.forEach((element) {
        ConversationMessage conversationMessage = ConversationMessage.fromJson(element.toJson());
        userIds.add(conversationMessage.targetId ?? "");

        conversationMessageList.add(conversationMessage);
      });

      //请求用户信息
      Map<String, Map<String, dynamic>> resultUserMap = await fetchAllUserInfo(userIds);
      for (var element in conversationMessageList) {
        element.name = resultUserMap[element.targetId]?["nickname"];
        element.headImageName = resultUserMap[element.targetId]?["headImageName"];
      }

      if (conversationMessageList.isNotEmpty) {
        dataList['技师信息'] = {'type': "IM", "group": conversationMessageList};
      }
      if (dataList.isEmpty) {
        setState(ViewState.empty);
      } else {
        setState(ViewState.normal);
      }
    }, onError: (int? code) {
      debugPrint("getRecentConversationList code ==  $code");
    }));
  }

  //更新最近的会话,  在聊天页面接收到消息后, 马上返回到消息列表页面, 会导致未读消息数量不对
  //isNeedAll是否更新全部
  updateRecentConversationList(String targetId, {bool isNeedAll = false}) async {
    debugPrint("获取会话 updateRecentConversationLis targetId ==  $targetId");

    if (conversationMessageList.isNotEmpty) {
      //更新当前的会话, 先找到当前的会话, 再去更新数据源
      await RCEngineManager().getConversation(targetId,
          callback: IRCIMIWGetConversationCallback(onSuccess: (RCIMIWConversation? tempConversation) async {
            //获取到当前人的会话
            ConversationMessage conversationMessage = ConversationMessage.fromJson(tempConversation!.toJson());

            //请求用户信息
            Map<String, Map<String, dynamic>> resultUserMap =
                await fetchAllUserInfo([conversationMessage.targetId ?? ""]);
            conversationMessage.name = resultUserMap[conversationMessage.targetId]?["nickname"];
            conversationMessage.headImageName = resultUserMap[conversationMessage.targetId]?["headImageName"];

            //更新会话
            int index = -1;
            for (var element in conversationMessageList) {
              if (element.targetId == conversationMessage.targetId) {
                index = conversationMessageList.indexOf(element);
                break;
              }
            }

            if (index >= 0) {
              if (isNeedAll) {
                conversationMessageList.removeAt(index);
                conversationMessageList.insert(0, conversationMessage);
              } else {
                conversationMessageList[index] = conversationMessage;
              }
            } else {
              conversationMessageList.insert(0, conversationMessage);
            }

            //更新数据源
            updateData("技师信息", conversationMessageList);
          }, onError: (int? code) {
            debugPrint("updateRecentConversationLis code ==  $code");
          }));
    } else {
      await getRecentConversationList();
      //获取所有的未读消息的数量, IM & 系统
      await getAllUnreadMessageCount();
    }
  }

  updateData(String dataKay, dynamic dataValue) async {
    Map<String, dynamic> contentMap = {};

    dataList.forEach((String key, value) {
      if (dataKay == key) {
        contentMap = dataList[key];
      }
    });

    // dataList['技师信息'] = {'type': "IM", "group": conversationMessageList};
    contentMap['group'] = dataValue;
    dataList[dataKay] = contentMap;

    notifyListeners();

    //获取所有的未读消息的数量, IM & 系统
    await getAllUnreadMessageCount();
  }

  //获取系统消息
  Future<void> requestSystemMessage() async {
    List<SysMessageModel> sysMessageModels = [];

    // 去请求服务器数据.
    Map<String, dynamic> resultMap = await DioHttpManager()
        .request(MyApi.getMemberNoticeList, method: DioHttpManager.post, data: {"page": "1", "limit": "2"});
    if (resultMap["code"] == 0) {
      List<dynamic> dataList = resultMap["data"];
      for (var element in dataList) {
        SysMessageModel sysMessageModel = SysMessageModel.fromMap(element);
        sysMessageModels.add(sysMessageModel);
      }
    }
    if (sysMessageModels.isNotEmpty) {
      dataList['系统消息'] = {'type': "sys", "group": sysMessageModels};
    }
    if (dataList.isEmpty) {
      setState(ViewState.empty);
    } else {
      setState(ViewState.normal);
    }
  }

  ///删除会话
  deleteConversation(String targetId, Function(int) callback) async {
    await RCEngineManager().removeConversation(targetId,
        callback: IRCIMIWRemoveConversationCallback(onConversationRemoved: (index) {
      if (index != null) {
        callback(index);
      }

      //如果会话删除完毕, 需要展示另外的页面
      bool isDataEmpty = true; //默认是没有数据的
      dataList.forEach((key, value) {
        if (key == "group") {
          List<dynamic> dynamicList = value;
          if (dynamicList.isNotEmpty) {
            isDataEmpty = false;
          }
        }
      });
      if (isDataEmpty) {
        setState(ViewState.empty);
      }
    }));
  }

  //获取IMUser的详情
  Future<Map<String, dynamic>> requestIMUserInfo(String imUser) async {
    // 去请求服务器数据.
    Map<String, dynamic> resultMap = await DioHttpManager()
        .request(MyApi.getUserInfoByImuser, method: DioHttpManager.post, data: {"im_user": imUser, "index_type": 2});

    if (resultMap["code"] == 0) {
      Map<String, dynamic> dataMap = resultMap["data"];

      final String tid = (dataMap["t_id"] ?? "").toString();
      if (tid.isNotEmpty) {
        dataMap['headImageName'] = dataMap['t_member_img'];
      } else {
        dataMap['headImageName'] = dataMap['member_img'];
      }
      return dataMap;
    }
    return {"nickname": "思思❤", "headImageName": "https://www.baidu.com/img/flexible/logo/pc/result.png"};
  }

  // 主函数，遍历用户ID列表并请求信息
  Future<Map<String, Map<String, dynamic>>> fetchAllUserInfo(List<String> userIds) async {
    Map<String, Map<String, dynamic>> userInfoMap = {};
    for (String userId in userIds) {
      // 请求用户信息
      Map<String, dynamic> userInfo = await requestIMUserInfo(userId);
      // 将用户信息添加到结果Map中
      userInfoMap[userId] = userInfo;
    }
    return userInfoMap;
  }
}

class ConversationMessage extends RCIMIWConversation {
  ///最后一条消息的时间
  String? lateMessageTime;
  String? name;
  String? headImageName;
  String lateMessageContent = "";

  ConversationMessage.fromJson(super.json) : super.fromJson() {
    //获取最后一条消息
    switch (lastMessage?.messageType) {
      case RCIMIWMessageType.text:
        //时间戳, 毫秒
        RCIMIWTextMessage message = lastMessage as RCIMIWTextMessage;
        // 获取最后一条消息的时间.
        lateMessageTime = CommonPlugin.messageTime(message.receivedTime ?? 0);
        lateMessageContent = message.text ?? "";

        break;
      case RCIMIWMessageType.image:
        //时间戳, 毫秒
        RCIMIWImageMessage message = lastMessage as RCIMIWImageMessage;
        // 获取最后一条消息的时间.
        lateMessageTime = CommonPlugin.messageTime(message.receivedTime ?? 0);
        lateMessageContent = "[图片]";
        break;
      default:
        lateMessageContent = MyConstant.notSupport;
    }
  }
}

//系统消息
class SysMessageModel {
  final int? id;
  final String? content;
  final int? createTime;
  final int? isSelect;
  final String? name;
  final String? img;
  final String? time;

  SysMessageModel({
    this.id,
    this.content,
    this.createTime,
    this.isSelect,
    this.name,
    this.img,
    this.time,
  });

  factory SysMessageModel.fromJson(String str) => SysMessageModel.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory SysMessageModel.fromMap(Map<String, dynamic> json) => SysMessageModel(
        id: json["id"],
        content: json["content"],
        createTime: json["create_time"],
        isSelect: json["is_select"],
        name: json["name"],
        img: json["img"],
        time: json["time"],
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "content": content,
        "create_time": createTime,
        "is_select": isSelect,
        "name": name,
        "img": img,
        "time": time,
      };
}
